package com.apes.scm.masterdata.product.service;

import com.apes.framework.api.DomainService;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.event.Listener;
import com.apes.scm.masterdata.multiKeys.CompanyProduct;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.product.model.CompanyProductUom;
import com.apes.scm.masterdata.product.model.Product;
import com.apes.scm.masterdata.product.model.ProductUom;
import com.apes.scm.masterdata.product.repository.CompanyProductUomRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * 功能：计量单位服务
 *
 * @author xul
 * @create 2018-03-08 11:14
 */
@Service("uomService")
public class UomService extends DomainService {

    @Autowired
    private CompanyProductUomRepository companyProductUomRepository;

    public CompanyProductUom save(SimpleRequest request) {
        CompanyProductUom uom = request.getO(CompanyProductUom.class);
        return companyProductUomRepository.saveAndFlush(uom);
    }

    /**
     * 功能：查询
     *
     * @param request
     */
    public List<CompanyProductUom> findAll(SimpleRequest request) {
        return companyProductUomRepository.findAll();
    }

    /*
     * 功能：公司商品基本计量单位
     */
    public ProductUom getUom(PartyRole company, Product product) {
        CompanyProduct keysClass = new CompanyProduct(company.getId(), product.getId());
        CompanyProductUom companyProductUom = companyProductUomRepository.findOne(keysClass);
        if (companyProductUom != null) return companyProductUom.getUom();
        return product.getUom();
    }

    @Listener(topic = "event:cm.product.uom.computeQty")
    public double computeQty(SimpleRequest request) {
        Map data = request.getMap();
        ProductUom formUom = (ProductUom) data.get("formUom");
        ProductUom toUom = (ProductUom) data.get("toUom");
        double inQty = (double) data.get("inQty");
        return formUom.computeQty(inQty, toUom, true);
    }

    @Listener(topic = "event:cm.product.uom.computePrice")
    public double computePrice(SimpleRequest request) {
        Map data = request.getMap();
        ProductUom formUom = (ProductUom) data.get("formUom");
        ProductUom toUom = (ProductUom) data.get("toUom");
        double price = (double) data.get("price");
        return formUom.computePrice(price, toUom);
    }
}
